package com.njtoyo.taxi.admin.logic.business.driver;

import com.njtoyo.taxi.admin.mongo.entity.secondary.AdminDeductDriverScoreLogMongo;
import com.njtoyo.taxi.admin.rest.wrapper.business.driver.ScoreDeductingLogQueryDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

@Service
public class ScoreDeductingLogLogic {
    @Autowired
    @Qualifier("secondaryMongoTemplate")
    private MongoTemplate secondaryMongoTemplate;

    public PageImpl<AdminDeductDriverScoreLogMongo> getList(ScoreDeductingLogQueryDto wrapper) {
        // 构造查询条件
        Query query = new Query();

        Sort sort = Sort.by(Sort.Order.desc("created_at"));
        Pageable pageable = PageRequest.of(wrapper.getCurrent(), wrapper.getSize(), sort);


        if (Objects.nonNull(wrapper.getDriverName())) {
            Pattern driverNamePattern = Pattern.compile(String.format("^.*%s.*$", wrapper.getDriverName()), Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("driver_name").regex(driverNamePattern));
        }

        if (Objects.nonNull(wrapper.getDriverPhone())) {
            Pattern driverMobileNumberPattern = Pattern.compile(String.format("^.*%s.*$", wrapper.getDriverPhone()), Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("driver_mobile_number").regex(driverMobileNumberPattern));
        }

        if (Objects.nonNull(wrapper.getAdminName())) {
            Pattern adminNamePattern = Pattern.compile(String.format("^.*%s.*$", wrapper.getAdminName()), Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("admin_name").regex(adminNamePattern));
        }

        if (Objects.nonNull(wrapper.getAdminPhone())) {
            Pattern adminMobileNumberPattern = Pattern.compile(String.format("^.*%s.*$", wrapper.getAdminPhone()), Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("admin_mobile_number").regex(adminMobileNumberPattern));
        }

        //计算总数
        long total = secondaryMongoTemplate.count(query, AdminDeductDriverScoreLogMongo.class);

        query.with(pageable);
        //查询结果集
        List<AdminDeductDriverScoreLogMongo> list = secondaryMongoTemplate.find(query, AdminDeductDriverScoreLogMongo.class);

        return new PageImpl<>(list, pageable, total);
    }
}
